package main

import (
	"fmt"
	"html/template"
	"log"
	"net/http"

	"golang.org/x/net/websocket"
)

func main() {
	var port = ":1234"
	http.Handle("/ws", websocket.Handler(Echo))
	//http.Handle("/", http.HandlerFunc(index))

	log.Printf("请访问 http://localhost%s\n",port)
	if err := http.ListenAndServe(port, nil); err != nil {
		log.Fatal("ListenAndServer: ", err)
	}
}

func Echo(ws *websocket.Conn) {
	var err error

	for {
		var reply string
		if err = websocket.Message.Receive(ws, &reply); err != nil {
			fmt.Println("Can't receive")
			break
		}

		fmt.Println("Received back from client: ", reply)

		msg := "Received: " + reply
		fmt.Println("Sending to client" + msg)

		if err = websocket.Message.Send(ws, msg); err != nil {
			fmt.Println("Can't send")
			break
		}
	}
}

func index(w http.ResponseWriter, r *http.Request) {
	if r.Method != "GET" {
		return
	}

	t, _ := template.ParseFiles("html/gochat.html")
	t.Execute(w, nil)
}